<style lang="less">
    @import "../../../styles/table.less";

    .product-wrap {
        display: flex;
        flex-wrap: wrap;

        .item {
            margin: 10px 20px 10px 20px;
        }

        .item-shop {
            margin: 10px 7px 10px 7px;
        }
    }
</style>
<template>
    <div class="search">

        <Row type="flex" justify="space-between" class="code-row-bg">

            <Col v-if="expand" span="5">
                <Card title="课程分类" style="height:100%">
                    <Row class="operation">
                        <Dropdown @on-click="addDropdownHandle">
                            <Button type="primary" @click="addCourseType">添加一级分类
                                <Icon type="md-arrow-dropdown"/>
                            </Button>
                            <DropdownMenu slot="list">
                                <DropdownItem name="addCourseTypeLevel">添加子分类</DropdownItem>
                            </DropdownMenu>
                        </Dropdown>

                        <Dropdown @on-click="handleDropdown">
                            <Button>更多
                                <Icon type="md-arrow-dropdown"/>
                            </Button>
                            <DropdownMenu slot="list">
                                <DropdownItem name="editCourseType">编辑分类</DropdownItem>
                                <DropdownItem name="delCourseType">删除分类</DropdownItem>
                                <DropdownItem name="refreshCourseType">刷新</DropdownItem>
                            </DropdownMenu>
                        </Dropdown>
                    </Row>
                    <Alert show-icon>
                        当前选择： <span class="select-title">{{editTitle}}</span>
                    </Alert>
                    <Input v-model="searchKey" suffix="ios-search" @on-change="search" placeholder="输入课程分类搜索" clearable/>
                    <div class="tree-bar">
                        <Tree ref="tree" :data="treeData" :load-data="loadData" @on-select-change="selectTree"></Tree>
                    </div>
                    <Spin size="large" fix v-if="treeLoading"></Spin>
                    <a href="#" slot="extra" @click.prevent="changeExpand">
                        <Tooltip content="折叠" placement="left">
                            <Icon type="md-arrow-round-back"/>
                        </Tooltip>
                    </a>
                </Card>
            </Col>

            <Col :span="span">
                <Card>
                    <Row>

                        <Form ref="searchForm" :model="searchForm" inline :label-width="70" class="search-form">
                            <Form-item label="课程名称" prop="courseTitle">
                                <Input type="text" v-model="searchForm.courseTitle" placeholder="请输入" clearable style="width: 200px"/>
                            </Form-item>
                            <Form-item label="课程状态" prop="courseStatus">
                                <Select v-model="searchForm.courseStatus" placeholder="请选择" clearable style="width:100px">
                                    <Option value="1">正常</Option>
                                    <Option value="0">已下架</Option>
                                </Select>
                            </Form-item>
                            <FormItem label="所属模块" prop="indextagId">
                                <Select v-model="searchForm.indextagId" style="width:100px">
                                    <Option v-for="item in indexTagList" :value="item.id" :key="item.id" :label="item.tagName">
                                    </Option>
                                </Select>
                            </FormItem>
                            <Form-item style="margin-left:-35px;" class="br">
                                <Button @click="handleSearch" type="primary" icon="ios-search">搜索</Button>
                                <Button @click="handleReset">重置</Button>
                            </Form-item>
                        </Form>
                    </Row>
                    <div class="left-operation-right">
                        <div>
                            <Tooltip content="请选项课程末级分类" placement="top" :disabled="!addCourseBtn">
                                <Button @click="addCourse" :disabled="addCourseBtn" type="primary" icon="md-add">添加</Button>
                            </Tooltip>
                            <Button @click="delAll" icon="md-trash">批量删除</Button>
                            <Button @click="getDataList" icon="md-refresh">刷新</Button>
                            <circleLoading v-if="operationLoading"/>
                        </div>

                    </div>
                    <div v-if="showType=='list'">
                        <Row>
                            <Alert show-icon>
                                已选择 <span class="select-count">{{selectCount}}</span> 项
                                <a class="select-clear" @click="clearSelectAll">清空</a>
                            </Alert>
                        </Row>
                        <Row>
                            <Table :loading="loading" border :columns="columns" :data="data" sortable="custom" @on-sort-change="changeSort" @on-selection-change="showSelect" ref="table"></Table>
                        </Row>
                    </div>

                    <Row type="flex" justify="end" class="page">
                        <Page :current="searchForm.pageNumber" :total="total" :page-size="searchForm.pageSize" @on-change="changePage" @on-page-size-change="changePageSize" :page-size-opts="[10,20,50]" size="small" show-total show-elevator show-sizer></Page>
                    </Row>
                    <p slot="title" @click.prevent="changeExpand">
                        <Icon v-if="!expand" type="md-arrow-round-forward"/>
                        课程管理
                    </p>
                </Card>

            </Col>
        </Row>
        <Modal v-model="picVisible" title="封面图" draggable>
            <img :src="fileUrl" alt="无效的图片链接" style="width: 100%;margin: 0 auto;display: block;">
        </Modal>
        <course-type-modal ref="courseType"></course-type-modal>
        <course-drawer ref="course"></course-drawer>
        <catlog-drawer ref="catlogDrawer"></catlog-drawer>
        <course-comment-drawer ref="coursecommentDrawer"></course-comment-drawer>
    </div>
</template>

<script>
    import {crouseList, delCrouseType, delCrouse, selectCourseType, setRecommend, setCourseStatus, selectIndexTag, setIndexTagId} from "@/api/bus";
    import circleLoading from "../../my-components/circle-loading.vue";
    import CatlogDrawer from "./catlogDrawer";
    import CourseCommentDrawer from "./coursecomment-drawer";

    export default {
        name: "courseManage",
        components: {
            CourseCommentDrawer,
            CatlogDrawer,
            circleLoading,
            courseDrawer: resolve => {
                require(['./course-drawer.vue'], resolve)
            },//懒加载
            courseTypeModal: resolve => {
                require(['./courseTypeModal.vue'], resolve)
            }
        },
        data() {
            return {
                treeLoading: false, // 树加载状态
                loading: false, // 表加载状态
                editTitle: "", // 编辑节点名称
                searchKey: "", // 搜索树
                expand: true,
                showType: "list",//数据展示方式
                expandIcon: "ios-arrow-back",
                selectNode: {},
                addCourseBtn: true,
                span: 19,
                treeData: [], // 树数据
                operationLoading: false, // 操作加载状态
                selectCount: 0, // 多选计数
                selectList: [], // 多选数据
                indexTagList: [],//课程模块
                fileUrl: "",
                picVisible: false,
                picTitle: "",
                searchForm: {
                    // 搜索框对应data对象
                    courseTitle: "",
                    courseStatus: -1,
                    indextagId: -1,
                    courseTypeId: "",
                    pageNumber: 1, // 当前页数
                    pageSize: 10, // 页面大小
                    sort: "c.createTime", // 默认排序字段
                    order: "desc" // 默认排序方式
                },
                modalType: 0, // 添加或编辑标识
                form: {
                    // 添加或编辑表单对象初始化数据
                    sex: 1,
                    parentId: 0,
                    type: 0
                },
                columns: [
                    {
                        type: "index",
                        width: 60,
                        align: "center",
                        fixed: "left"
                    }, {
                        type: "selection",
                        width: 60,
                        align: "center",
                        fixed: "left"
                    },
                    {
                        title: "课程名称",
                        key: "courseTitle",
                        ellipsis: true,
                        tooltip: true,
                        width: 150,
                        sortable: true
                    },
                    {
                        title: "封面图",
                        key: "courseImage",
                        width: 120,
                        align: "center",
                        render: (h, params) => {
                            return h("img", {
                                attrs: {
                                    src: params.row.courseImage,
                                    alt: "加载图片失败"
                                },
                                style: {
                                    cursor: "pointer",
                                    width: "80px",
                                    height: "60px",
                                    margin: "3px 0",
                                    "object-fit": "contain"
                                },
                                on: {
                                    click: () => {
                                        this.showPic(params.row.courseImage);
                                    }
                                }
                            });

                        }
                    },
                    {
                        title: "分类",
                        key: "courseTypeName",
                        width: 120,
                        sortable: true
                    },
                    {
                        title: "价格",
                        key: "coursePrice",
                        width: 80,
                        sortable: true
                    },
                    {
                        title: "讲师",
                        key: "userName",
                        width: 100,
                        sortable: true
                    },
                    {
                        title: "推荐",
                        key: "recommend",
                        align: "center",
                        hidden: true,
                        width: 80,
                        render: (h, params) => {
                            return h(
                                "i-switch",
                                {
                                    props: {
                                        value: params.row.recommend,
                                        size: "large",
                                        "true-value": 1,
                                        "false-value": 0
                                    },
                                    on: {
                                        "on-change": v => {
                                            this.setRecommend(params.row, v);
                                        }
                                    }
                                },
                                [
                                    h("span", {slot: "open"}, "是"),
                                    h("span", {slot: "close"}, "否")
                                ]
                            );
                        }
                    },
                    {
                        title: "上架",
                        key: "courseStatus",
                        align: "center",
                        width: 80,
                        render: (h, params) => {
                            return h(
                                "i-switch",
                                {
                                    props: {
                                        value: params.row.courseStatus,
                                        size: "large",
                                        "true-value": 1,
                                        "false-value": 0
                                    },
                                    on: {
                                        "on-change": v => {
                                            this.setCourseStatus(params.row, v);
                                        }
                                    }
                                },
                                [
                                    h("span", {slot: "open"}, "是"),
                                    h("span", {slot: "close"}, "否")
                                ]
                            );
                        }
                    },
                    {
                        title: "首页模块",
                        key: "indextagId",
                        width: 150,
                        render: (h, params) => {
                            return h('Select',
                                {
                                    props: {
                                        value: params.row.indextagId,
                                    },
                                    on: {
                                        "on-change": v => {
                                            this.setIndexTagId(params.row.id, v);
                                        }
                                    }
                                },
                                this.indexTagList.map((item) => {
                                    return h('Option', {
                                        props: {
                                            value: item.id,
                                            label: item.tagName
                                        }
                                    })
                                }))
                        }
                    },
                    {
                        title: "排序",
                        key: "sortOrder",
                        width: 120,
                        sortable: true,
                    },
                    {
                        title: "创建时间",
                        key: "createTime",
                        width: 200,
                        sortable: true,
                        sortType: "desc"
                    },
                    {
                        title: "赠送积分",
                        key: "scoreCourse",
                        width: 120,
                        sortable: true,
                    },
                    {
                        title: "操作",
                        key: "action",
                        width: 280,
                        align: "center",
                        fixed: "right",
                        render: (h, params) => {
                            return h("div", [
                                h(
                                    "Button",
                                    {
                                        props: {
                                            type: "warning",
                                            size: "small"
                                        },
                                        style: {
                                            marginRight: "5px"
                                        },
                                        on: {
                                            click: () => {
                                                this.$refs.catlogDrawer.show(params.row);
                                            }
                                        }
                                    },
                                    "课程目录"
                                ), h(
                                    "Button",
                                    {
                                        props: {
                                            type: "primary",
                                            size: "small"
                                        },
                                        style: {
                                            marginRight: "5px"
                                        },
                                        on: {
                                            click: () => {
                                                this.edit(params.row);
                                            }
                                        }
                                    },
                                    "编辑"
                                ),
                                h(
                                    "Button",
                                    {
                                        props: {
                                            type: "primary",
                                            size: "small"
                                        },
                                        style: {
                                            marginRight: "5px"
                                        },
                                        on: {
                                            click: () => {
                                                this.commentList(params.row);
                                            }
                                        }
                                    },
                                    "评论管理"
                                ),
                                h(
                                    "Button",
                                    {
                                        props: {
                                            type: "error",
                                            size: "small"
                                        },
                                        on: {
                                            click: () => {
                                                this.remove(params.row);
                                            }
                                        }
                                    },
                                    "删除"
                                )
                            ]);
                        }
                    }
                ],
                data: [], //表单数据
                total: 0// 表单数据总数
            };
        },
        methods: {
            init() {
                this.getTreeData();
                this.getIndexTag();
                this.getDataList();
            },
            changeExpand() {
                this.expand = !this.expand;
                if (this.expand) {
                    this.expandIcon = "ios-arrow-back";
                    this.span = 19;
                } else {
                    this.expandIcon = "ios-arrow-forward";
                    this.span = 24;
                }
            },
            renderContent(h, {root, node, data}) {
                if (data.isParent) {
                    return h(
                        "span",
                        {
                            style: {
                                display: "inline-block",
                                cursor: "pointer"
                            },
                            on: {
                                click: (e) => {
                                    this.selectTree(data);
                                }
                            }
                        },
                        [
                            h("span", [
                                h("img", {
                                    attrs: {
                                        src: data.typeImg,
                                        alt: "..."
                                    },
                                    domProps: {
                                        className: 'btn'
                                    },
                                    style: {
                                        cursor: "pointer",
                                        width: "17px",
                                        height: "17px",
                                        "margin-right": "5px"
                                    }
                                }),
                                h("span", data.title)
                            ])
                        ]
                    );
                } else {

                    return h(
                        "span",
                        {
                            style: {
                                display: "inline-block",
                                cursor: "pointer"
                            },
                            on: {
                                click: (e) => {
                                    this.selectTree(data);
                                }
                            }
                        }, data.title
                    );

                }


            },
            //加载一级课程类型
            getTreeData() {
                this.treeLoading = true;
                selectCourseType({parentId: 0}).then(res => {
                    this.treeLoading = false;
                    if (res.status === true) {
                        this.treeData = res.data;
                    }
                });
            },
            //加载课程所属模块
            getIndexTag() {
                this.treeLoading = true;
                selectIndexTag().then(res => {
                    this.treeLoading = false;
                    if (res.status === true) {
                        this.indexTagList = res.data;
                    }
                });
            },
            //加载二级课程类型
            loadData(item, callback) {
                selectCourseType({parentId: item.id}).then(res => {
                    if (res.status === true) {
                        callback(res.data);
                    }
                });
            },
            //添加下拉按钮事件
            addDropdownHandle(name) {
                switch (name) {
                    case 'addCourseTypeLevel':
                        if (this.form.parentId == 0) {
                            this.$Message.warning("请选择父级节点");
                            return;
                        }
                        if (this.selectNode.parentId != "0") {
                            this.$Message.warning("只能创建二级分类");
                            return;
                        }
                        console.info(JSON.stringify(this.selectNode))
                        this.$refs.courseType.add(this.selectNode);
                        break;
                }
            },
            showPic(v) {
                this.fileUrl = v;
                this.picVisible = true;
            },
            //更多下拉按钮事件
            handleDropdown(name) {
                switch (name) {
                    case 'addCourseTypeLevel':
                        this.$refs.courseType.add();
                        break;
                    case 'editCourseType':
                        if (!this.selectNode.id) {
                            this.$Message.warning("请选择节点");
                            return;
                        }
                        this.$refs.courseType.edit(this.selectNode);
                        break;
                    case 'refreshCourseType':
                        this.getTreeData();
                        this.addCourseBtn = true;
                        this.searchForm.courseTypeId = "";
                        break;
                    case 'delCourseType':
                        this.delCourseType();
                        break;
                }
            },
            //添加一级课程分类
            addCourseType() {
                this.$refs.courseType.add();
            },
            //删除课程分类
            delCourseType() {
                if (!this.selectNode.id) {
                    this.$Message.warning("请选择删除项目");
                    return;
                }
                if (this.selectNode.isParent === 1) {
                    this.$Message.error("该分类下有二级分类，无法删除");
                    return;
                }
                this.$Modal.confirm({
                    title: "确认删除",
                    loading: true,
                    content: "您确认要删除 " + this.selectNode.title + " ?",
                    onOk: () => {
                        // 删除
                        delCrouseType(this.selectNode.id).then(res => {
                            this.$Modal.remove();
                            if (res.status === true) {
                                this.$Message.success("删除成功");
                                this.getTreeData();
                            }
                        });
                    }
                });
            },
            //添加课程
            addCourse() {
                let query = {type: 0, courseTypeId: this.selectNode.id, backRoute: this.$route.name}
                /* this.$router.push({
                     name: "add_course",
                     query: query
                 });*/
                this.$refs.course.showCourseDrawer(query);
            },
            //设置课程推荐状态
            setRecommend(row, v) {
                let params = {
                    courseId: row.id,
                    recommend: v
                }
                setRecommend(params).then(res => {
                    if (res.status === true) {
                        this.$Message.success(res.info);
                    }
                });
                ;
            },
            //设置课程所属模块
            setIndexTagId(id, indextagId) {
                let params = {
                    id, indextagId
                }
                setIndexTagId(params).then(res => {
                    if (res.status === true) {
                        this.$Message.success(res.info);
                    }
                });
                ;
            },
            //设置课程推荐状态
            setCourseStatus(row, v) {
                let params = {
                    courseId: row.id,
                    courseStatus: v
                }
                setCourseStatus(params).then(res => {
                    if (res.status === true) {
                        this.$Message.success(res.info);
                    }
                });
                ;
            },
            //课程分类查询
            search() {
                let params = {}
                // 搜索树
                if (this.searchKey) {
                    params.title = this.searchKey;
                } else {
                    params.parentId = 0;
                    params.title = "";
                }
                selectCourseType(params).then(res => {
                    this.treeLoading = false;
                    if (res.status === true) {
                        this.treeData = res.data;
                    }
                });
            },
            //课程分类选择事件
            selectTree(v) {
                if (v) {
                    for (let attr in v) {
                        if (v[attr] === null) {
                            v[attr] = "";
                        }
                    }
                    let str = JSON.stringify(v[0]);
                    let data = JSON.parse(str);
                    this.selectNode = data;
                    if (this.selectNode.parentId == "0") {
                        this.searchForm.courseTypeId = data.id;
                        this.form.parentId = data.id;
                        this.addCourseBtn = true;
                    } else {
                        this.searchForm.courseTypeId = data.id;
                        this.addCourseBtn = false;
                    }
                    this.editTitle = data.title;
                    // 重新加载表
                    this.getDataList();
                } else {
                    this.addCourseBtn = true;
                    this.searchForm.courseTypeId = "";
                }
            },
            changeSelect(v) {
                this.selectCount = v.length;
                this.selectList = v;
            },
            changePage(v) {
                this.searchForm.pageNumber = v;
                this.getDataList();
                this.clearSelectAll();
            },
            changePageSize(v) {
                this.searchForm.pageSize = v;
                this.getDataList();
            },
            changeShowType() {
                this.searchForm.pageNumber = 1;
                if (this.showType == "list") {
                    this.searchForm.pageSize = 5;
                } else {
                    this.searchForm.pageSize = 12;
                }
                this.getDataList();
            },
            getDataList() {
                this.loading = true;
                crouseList(this.searchForm).then(res => {
                    this.loading = false;
                    if (res.status === true) {
                        this.data = res.data.rows;
                        this.total = res.data.total;
                    }
                });
            },
            handleSearch() {
                this.searchForm.pageNumber = 1;
                this.searchForm.pageSize = 10;
                this.getDataList();
            },
            handleReset() {
                this.$refs.searchForm.resetFields();
                this.searchForm.pageNumber = 1;
                this.searchForm.pageSize = 10;
                // 重新加载数据
                this.getDataList();
            },
            changeSort(e) {
                this.searchForm.sort = e.key;
                this.searchForm.order = e.order;
                if (e.order === "normal") {
                    this.searchForm.order = "";
                }
                this.getDataList();
            },
            showSelect(e) {
                this.selectList = e;
                this.selectCount = e.length;
            },
            commentList(row) {
                let query = {courseId: row.id};
                this.$refs.coursecommentDrawer.showDrawer(query);
            },
            clearSelectAll() {
                this.$refs.table.selectAll(false);
            },
            edit(v) {
                let query = {type: 1, courseId: v.id, backRoute: this.$route.name};
                /* this.$router.push({
                     name: "add_course",
                     query: query
                 });*/
                this.$refs.course.showCourseDrawer(query);
            },
            remove(v) {
                this.$Modal.confirm({
                    title: "确认删除",
                    content: "您确认要删除?",
                    onOk: () => {
                        delCrouse(v.id).then(res => {
                            if (res.status === true) {
                                this.$Message.success("删除成功");
                                this.getDataList();
                            }
                        });
                    }

                });
            },
            delAll() {
                if (this.selectCount <= 0) {
                    this.$Message.warning("您还未选择要删除的数据");
                    return;
                }
                this.$Modal.confirm({
                    title: "确认删除",
                    content: "您确认要删除所选的 " + this.selectCount + " 条数据?",
                    onOk: () => {
                        let ids = [];
                        this.selectList.forEach(function (e) {
                            ids.push(e.id);
                        });
                        delCrouse(ids).then(res => {
                            if (res.status === true) {
                                this.$Message.success("删除成功");
                                this.getDataList();
                                this.clearSelectAll();
                            }
                        });
                    }
                });
            }
        },
        mounted() {
            this.init();
        }
    };
</script>